<script lang="jsx" setup>
import { computed, nextTick, onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import { useElementSize } from '@vueuse/core';
import { useRoute } from 'vue-router';
import { Input, message } from 'ant-design-vue';
import { getAllForms } from '@/service/api/modules/check-inventory-manage/form-setup';
import {
  auditData,
  deleteDataForm,
  getRightData,
  updateData,
  updateDataForm,
  withdrawal
} from '@/service/api/modules/check-inventory-manage/records';

const route = useRoute();
const commonSearchRef = ref(null);

const { height } = useElementSize(commonSearchRef);
const stateOptions = ref([]);

const id = getfileName();
const searchParams = ref({
  hasIpqc: null,
  inspectionMachineNo: null,
  inspectionState: null,
  inspectionFormId: id,
  time: null
});
const formData = ref({});
function getfileName() {
  const fullPathArr = route.fullPath.split('/');
  return fullPathArr[fullPathArr.length - 1];
}
async function getFormData() {
  const { data, error } = await getAllForms();
  if (!error) {
    formData.value = data?.find(item => item.id === Number(id));
    searchParams.value.hasIpqc = formData.value.hasIpqc;
    getStateOptions();
    search();
  }
}

const btnAuth = ref({
  del: `check-inventory-manage:records:${id}:del`, // 删除权限
  IPQCExamine: `check-inventory-manage:records:${id}:IPQCExamine`, // IPQC/QA审核权限
  foremanAudit: `check-inventory-manage:records:${id}:foremanAudit`, // 领班审核权限
  supervisorAudit: `check-inventory-manage:records:${id}:supervisorAudit`, // 主管审核权限
  withdrawTrial: `check-inventory-manage:records:${id}:withdrawTrial`, // 撤审权限
  update: `check-inventory-manage:records:${id}:update`, // 修改权限
  edit: `check-inventory-manage:records:${id}:edit` // 编辑权限
});

function getStateOptions() {
  if (Number(formData.value.hasIpqc) === 0) {
    stateOptions.value = [
      {
        label: '待IPQC审核',
        value: 0
      },
      {
        label: '待修改',
        value: 1
      },
      {
        label: '待主管审核',
        value: 2
      },
      {
        label: '审核完成',
        value: 3
      },
      {
        label: '待领班审核',
        value: 4
      }
    ];
  } else {
    stateOptions.value = [
      {
        label: '待领班审核',
        value: 0
      },
      {
        label: '待修改',
        value: 1
      },
      {
        label: '待主管审核',
        value: 2
      },
      {
        label: '审核完成',
        value: 3
      }
    ];
  }
}

onMounted(() => {
  getFormData();
});

// const formList = ref([]);
const searchFormList = [
  // {
  //   type: 'select',
  //   key: 'form',
  //   label: '关联表单',
  //   placeholder: '请输入关联表单',
  //   span: 24,
  //   md: 12,
  //   lg: 5,
  //   xl: 5,
  //   xxl: 4,
  //   search: true,
  //   selectOptions: formList,
  //   change(val) {
  //     searchParams.value.inspectionFormId = formList.value.find(item => item.value === val).id;
  //   }
  // },
  {
    type: 'input',
    key: 'inspectionMachineNo',
    label: '机台号',
    placeholder: '请输入机台号',
    span: 24,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4
  },
  {
    type: 'select',
    key: 'inspectionState',
    label: '状态',
    placeholder: '请选择状态',
    span: 24,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4,
    selectOptions: stateOptions
  },
  {
    type: 'select',
    key: 'shiftType',
    label: '班别',
    placeholder: '请输入班别',
    span: 24,
    md: 12,
    lg: 5,
    xl: 5,
    xxl: 4,
    selectOptions: [
      { label: '白班', value: '0' },
      { label: '夜班', value: '1' }
    ]
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '日期',
    span: 24,
    md: 12,
    lg: 10,
    xl: 8,
    xxl: 6,
    showTime: true
  }
];
const tableRef = ref(null);
const searchData = computed(() => {
  const params = {
    ...searchParams.value
  };
  if (searchParams.value?.time?.[0]) {
    params.startTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD HH:mm:ss');
    params.endTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD 23:59:59');
  }
  delete params.time;
  return params;
});

const tableSelect = ref([]);
const currentLeftRow = ref(null);
function tableSelectChange(val) {
  tableSelect.value = val;
}

const column = ref([
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  // {
  //   key: 'inspectionFormName',
  //   dataIndex: 'inspectionFormName',
  //   title: '表单名称',
  //   width: 150,
  //   align: 'center',
  //   checked: true,
  //   ellipsis: true
  // },
  {
    key: 'inspectionFormCode',
    dataIndex: 'inspectionFormCode',
    title: '表单编号',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionOperater',
    dataIndex: 'inspectionOperater',
    title: '点检人',
    align: 'center',
    width: 100,
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionTime',
    dataIndex: 'inspectionTime',
    title: '点检时间',
    width: 170,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionMachineNo',
    dataIndex: 'inspectionMachineNo',
    title: '机台号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inspectionState',
    dataIndex: 'inspectionState',
    title: '状态',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      // 有IPQC审核的表单
      if (Number(record.hasIpqc) === 0) {
        return ['待IPQC审核', '待修改', '待主管审核', '审核完成', '待领班审核'][record.inspectionState];
      }
      // 有FQA审核的表单
      if (record.hasFqa !== null && Number(record.hasFqa) === 0) {
        return ['待FQA审核', '待修改', '待主管审核', '审核完成', '待领班审核'][record.inspectionState];
      }
      return ['待领班审核', '待修改', '待主管审核', '审核完成'][record.inspectionState];
    }
  },
  {
    key: 'shiftType',
    dataIndex: 'shiftType',
    title: '班别',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return ['白班', '夜班'][record.shiftType];
    }
  },
  {
    key: 'inspectionAbnormalState',
    dataIndex: 'inspectionAbnormalState',
    title: '异常信息',
    width: 170,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'foreman',
    dataIndex: 'foreman',
    title: '领班审核',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'foremanTime',
    dataIndex: 'foremanTime',
    title: '领班审核时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'examiner',
    dataIndex: 'examiner',
    title: '主管审核',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'examinerTime',
    dataIndex: 'examinerTime',
    title: '主管审核时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createrName',
    dataIndex: 'createrName',
    title: '创建人',
    width: 130,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  }
]);

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    // searchParams.value = {
    //   form: null,
    //   inspectionMachineNo: null,
    //   inspectionMachineNo: null,
    //   inspectionFormId: id,
    //   time: null
    // };
    searchParams.value.inspectionMachineNo = null;
    searchParams.value.inspectionState = null;
    searchParams.value.shiftType = null;
    searchParams.value.time = null;
    search();
  });
}

const { handleClose, handleLoading, handleShow } = window.$useModal({
  modalOption: {
    title: '修改异常信息',
    destroyOnClose: true,
    width: 600,
    height: 220,
    confirmBtnText: '保存'
  },
  formList: [
    {
      type: 'textarea',
      key: 'inspectionAbnormalState',
      label: '异常信息',
      placeholder: '请输入异常信息',
      span: 24,
      rule: {
        required: true,
        message: '请输入异常信息',
        trigger: 'change'
      }
    }
  ],
  formData: {
    inspectionAbnormalState: null
  },
  onOk: data => {
    handleLoading(true);
    updateData(data)
      .then(({ error }) => {
        handleLoading(false);
        if (!error) {
          message.success('修改成功!');
          tableRef.value.getData();
          tableRef.value.tableSelectChange([]);
          handleClose();
        }
      })
      .finally(() => {
        handleLoading(false);
      });
  }
});

function handleUpdate() {
  if (!tableSelect.value.length) {
    message.error('请选择要修改的数据!');
    return;
  }
  handleShow(tableSelect.value[0]);
}

// 审核
function handleApproval(state) {
  if (!tableSelect.value.length) {
    message.error('请选择要审核的数据!');
    return;
  }
  const data = tableSelect.value.map(item => {
    return {
      ...item,
      inspectionState: state
    };
  });
  window.$modal.confirm({
    title: '确定进行批量审核吗?',
    onOk: () => {
      // return instance.post('/agv/Exporter/updateBatch',data);
      auditData(data).then(({ error }) => {
        if (!error) {
          message.success('批量审核成功!');
          tableRef.value.tableSelectChange([]);
          tableRef.value.getData();
          if (currentLeftRow.value) {
            currentLeftRow.value.inspectionState = state;
          }
        }
      });
    },
    onCancel: () => {}
  });
}

// 删除
function handleDel() {
  if (!tableSelect.value.length) {
    message.error('请选择要删除的数据!');
    return;
  }
  window.$modal.confirm({
    title: '确定进行批量删除吗?',
    onOk: () => {
      deleteDataForm([...tableSelect.value]).then(({ error }) => {
        if (!error) {
          message.success('批量删除成功!');
          commonSearchRef.value.formReset();
          tableRef.value.tableSelectChange([]);
          rightTableData.value = [];
        }
      });
    },
    onCancel: () => {}
  });
}

// 撤审
function handleFallback() {
  if (!tableSelect.value.length) {
    message.error('请选择要撤审的数据!');
    return;
  }
  window.$modal.confirm({
    title: '确定进行撤审吗?',
    onOk: () => {
      withdrawal(tableSelect.value).then(({ error }) => {
        if (!error) {
          message.success('撤审成功!');
          tableRef.value.tableSelectChange([]);
          tableRef.value.getData();
          if (currentLeftRow.value) {
            currentLeftRow.value.inspectionState = 1;
          }
        }
      });
    },
    onCancel: () => {}
  });
}

// 右边部分
const rightTableRef = ref(null);
const rightTableData = ref([]);
const rightColumn = ref([
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemProcess',
    dataIndex: 'itemProcess',
    title: '流程',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemName',
    dataIndex: 'itemName',
    title: '点检项目',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemStardard',
    dataIndex: 'itemStardard',
    title: '标准',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemFrequence',
    dataIndex: 'itemFrequence',
    title: '频率',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemValue',
    dataIndex: 'itemValue',
    title: '点检内容',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record, index }) => {
      if ([0, 1].includes(Number(currentLeftRow.value.inspectionState))) {
        return <Input v-model:value={rightTableRef.value.tableData[index].itemValue}></Input>;
      }
      return record.itemValue;
    }
  }
]);

function checkHasEditAuth() {
  if (window.$utils.checkAuth([btnAuth.value.update])) {
    rightColumn.value.push({
      key: 'cz-Col',
      dataIndex: 'cz-Col',
      title: '操作',
      width: 100,
      align: 'center',
      fixed: 'right',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        if ([0, 1].includes(Number(currentLeftRow.value.inspectionState))) {
          return (
            <a
              class="mr-10px color-blue"
              onClick={() => {
                handleSave(record);
              }}
            >
              保存
            </a>
          );
        }
        return '';
      }
    });
  }
}

checkHasEditAuth();

function tableRowClick(val) {
  currentLeftRow.value = val;
  getRightTableData();
}

// 获取右边表格数据
function getRightTableData() {
  getRightData(currentLeftRow.value.id, id).then(({ data, error }) => {
    if (!error) {
      data.forEach((item, index) => {
        item.dataIndex = index + 1;
        item.isEdit = false;
      });
      rightTableData.value = data;
    }
  });
}

// 保存
function handleSave(record) {
  updateDataForm({ ...record }).then(({ error }) => {
    if (!error) {
      window.$message.success('保存成功!');
      getRightTableData();
      tableRef.value.getData();
    }
  });
}

const tableCustomRow = record => {
  return {
    style: Number(record.isOk) === 1 ? { background: '#f76d6d' } : {}
  };
};
</script>

<template>
  <div class="check-inventory-records-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>
    <div class="table-content w-full" :style="{ height: `calc(100% - ${height}px)` }">
      <ARow :gutter="8" class="h-full">
        <ACol :span="14" class="h-full">
          <Table
            ref="tableRef"
            v-model:searchParams="searchData"
            class="h-full"
            :column="column"
            show-row-selection
            row-key="id"
            :scroll="{ y: 'auto' }"
            :is-init-get-data="true"
            url="/inspection/inspectionData/selectDataForms"
            :table-custom-row="tableCustomRow"
            @table-select-change="tableSelectChange"
            @table-row-click="tableRowClick"
          >
            <template #title>
              <AButton
                v-hasAuth="[btnAuth.update]"
                type="primary"
                size="small"
                ghost
                class="mini-btn mr-8px"
                :disabled="tableSelect.length !== 1"
                @click="handleUpdate"
              >
                <template #icon>
                  <icon-ic-round-edit class="align-sub text-icon" />
                </template>
                <span class="ml-3px">修改</span>
              </AButton>
              <AButton
                v-hasAuth="[btnAuth.del]"
                type="primary"
                size="small"
                danger
                ghost
                class="mini-btn mr-8px"
                :disabled="!tableSelect.length"
                @click="handleDel"
              >
                <template #icon>
                  <icon-ic-round-delete class="align-sub text-icon" />
                </template>
                <span class="ml-3px">删除</span>
              </AButton>
              <AButton
                v-if="Number(formData.hasIpqc) === 0"
                v-hasAuth="[btnAuth.IPQCExamine]"
                type="primary"
                size="small"
                ghost
                class="mini-btn mr-8px"
                :disabled="!tableSelect.length"
                @click="handleApproval(4)"
              >
                <template #icon>
                  <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
                </template>
                <span class="ml-3px">IPQC审核</span>
              </AButton>
              <AButton
                v-if="Number(formData.hasFqa) === 0"
                v-hasAuth="[btnAuth.IPQCExamine]"
                type="primary"
                size="small"
                ghost
                class="mini-btn mr-8px"
                :disabled="!tableSelect.length"
                @click="handleApproval(4)"
              >
                <template #icon>
                  <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
                </template>
                <span class="ml-3px">FQA审核</span>
              </AButton>
              <AButton
                v-hasAuth="[btnAuth.foremanAudit]"
                type="primary"
                size="small"
                ghost
                class="mini-btn mr-8px"
                :disabled="!tableSelect.length"
                @click="handleApproval(2)"
              >
                <template #icon>
                  <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
                </template>
                <span class="ml-3px">领班审核</span>
              </AButton>
              <AButton
                v-hasAuth="[btnAuth.supervisorAudit]"
                type="primary"
                size="small"
                ghost
                class="mini-btn mr-8px"
                :disabled="!tableSelect.length"
                @click="handleApproval(3)"
              >
                <template #icon>
                  <span class="iconfont icon-shenhe" style="font-size: 14px"></span>
                </template>
                <span class="ml-3px">主管审核</span>
              </AButton>
              <AButton
                v-hasAuth="[btnAuth.withdrawTrial]"
                type="primary"
                size="small"
                ghost
                class="mini-btn mr-8px"
                :disabled="!tableSelect.length"
                @click="handleFallback"
              >
                <template #icon>
                  <span class="iconfont icon-cheshenanniu" style="font-size: 14px"></span>
                </template>
                <span class="ml-3px">撤审</span>
              </AButton>
            </template>
            <template #footer>
              <div ref="tableFooterRef" style="display: flex; align-items: center">
                <div style="width: 20px; height: 14px; background-color: rgb(247, 109, 109)"></div>
                <span>背景为异常</span>
              </div>
            </template>
          </Table>
        </ACol>
        <ACol :span="10" class="h-full">
          <Table
            ref="rightTableRef"
            v-model:searchParams="searchData"
            :data-source="rightTableData"
            class="h-full"
            :column="rightColumn"
            :show-row-selection="false"
            row-key="id"
            :scroll="{ y: 'auto' }"
            is-init-get-data
            :row-height="40"
            :table-custom-row="tableCustomRow"
          >
            <template #footer>
              <div ref="tableFooterRef" style="display: flex; align-items: center">
                <div style="width: 20px; height: 14px; background-color: rgb(247, 109, 109)"></div>
                <span>背景为异常</span>
              </div>
            </template>
          </Table>
        </ACol>
      </ARow>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.table-content {
  padding: 8px;
}
</style>
